<template>
	<view style="padding: 10px;">
		<view>
			<u-form>
				<u-form-item label="日期:"  border-bottom="false" label-width="150" >
					<u-input v-model="formData.time" @click="show=!show" disabled="true" border="true"  />
				</u-form-item>
				<u-form-item label="事项:"  border-bottom="false" label-width="150" >
					<u-input v-model="formData.sx" :disabled="disabled" />
				</u-form-item>
				<u-form-item label="处理结果:"  border-bottom="false"  label-width="150" >
					<u-radio-group v-model="formData.result">
						<u-radio 
							@change="radioChange" 
							v-for="(item, index) in results" :key="index" 
							:name="item.value"
							:disabled="disabled"
						>
							{{item.label}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="照片:"  border-bottom="false" label-width="150" >
					<u-upload :disabled="disabled" :file-list="imgList" ref="imgUpload" :name="name"  @on-uploaded="onUploaded" :action="action" @on-remove="onRemove" ></u-upload>
					<view v-if="disabled">
						<image class="uploadImg" @click.prevent.stop="previewImg(imgPath.url)" v-for="imgPath in imgList" :src="imgPath.url" mode=""></image>
					</view>
				</u-form-item>
				<u-form-item label="签名:"  :border-bottom="border_bottom"  label-width="150" />
				<view class="wrapper" v-bind:class="[show && !disabled ? 'hideSign' : 'showSign']" >
					<view v-if="!hasSign" >
						<view class="handCenter">
							<canvas class="handWriting" disable-scroll="true" @touchstart="uploadScaleStart" @touchmove="uploadScaleMove"
							  @touchend="uploadScaleEnd" @tap="mouseDown" canvas-id="handWriting">
							</canvas>
						 </view>
						<view class="buttons">
							<button @click="retDraw" class="delBtn">重签</button>
							<button @click="subCanvas" :disabled="qmBtn" class="subBtn">完成签名</button>	
						</view>
					</view>
					<view v-if="hasSign" class="showimg">
						<image  :src="signImageURL" mode=""></image>
					</view>
					<u-button v-if="!disabled"  @click="save(1,false)" :disabled="submitBtn" type="primary" class="commitBtn">保存</u-button>
					
				</view>
			</u-form>
			<view class="buttons" v-if="hasChecked">
				<u-button  @click="checked()" :disabled="submitBtn" type="primary">审核通过</u-button>
				<u-button  @click="unChecked()" :disabled="submitBtn" type="success">审核不通过</u-button>
			</view>
			<u-modal show-cancel-button="true"  @confirm="confirm" v-model="unCheckedModalShow" :title="content" >
				<view style="padding: 10px;">
					<u-input v-model="formData.unCheckedReason" border="true" type="textarea" :auto-height="true" />
				</view>
				
			</u-modal>
		</view>
		<cus-previewImg ref="cusPreviewImg" :list="cusPreviewImgList" />
		<u-calendar v-if="!disabled"  v-model="show" :mode="mode" @change="change"></u-calendar>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { mapState} from 'vuex';
	import Handwriting from "@/utils/signature.js"
	import cusPreviewImg from '@/components/cus-previewImg/cus-previewImg.vue'
	
	export default {
		components:{cusPreviewImg},
		computed:mapState(['user', ]),
		data() {
			return {
				hasChecked:false,	//是否有审核权限
				content:'请输入原因',
				disabled:false,		//控制回显数据是否可编辑
				qmBtn:false,
				unCheckedModalShow:false,	//审核不通过模态窗显示标记
				border_bottom:false,
				lineColor:'black',
				slideValue:50,
				handwriting:'',
				signImage: '',
				signImageURL: '',
				isEnd: false , // 是否签名
				hasSign:false,	//是否已存在签名，用于之前已经签过名，后面重新进入
				url: this.$http.config.baseURL+'/fwqz/save',	//最后提交结果的地址
				imgList:[],
				cusPreviewImgList:[],	//点击查看图片列表
				submitBtn:false,
				action: this.$http.config.baseURL+'/fwqz/upload',	//图片上传地址
				name: 'files',
				formData:{
					id:'',
					time: this.$util.getNowD(),
					sx: '',
					result: '1',
					filePaths: '',
					location: '',
					lat: '',
					lng: '',
					userId: '',
					state: '1',
					qmPath:'',
					unCheckedReason:''
				},
				results: [
					{
						value: '1',
						label: '满意'
					},
					{
						value: '0',
						label: '不满意'
					}
				],
				fileList: [],
				show: false,
				mode: 'date',
				
			}
		},
		methods:{	
			change(e){
				//时间选择事件
				this.formData.time  = e.result;
			},
			// 选中某个单选框时，由radio时触发
			radioChange(e) {
				this.formData.result = e;
			},
			// 数据校验
			validateFormData(){
				let flag = true;
				if(this.formData.sx === undefined || this.formData.sx === ''){
					this.$refs.uToast.show({
						title: '请填写服务事项',
						type: 'error'
					})
					flag = false;
					return flag;
				}
				if(!this.signImage){
					this.$refs.uToast.show({
						title: '请完成签名后提交',
						type: 'error'
					})
					flag = false;
					return flag;
				}
				return flag;
			},
			save(sta,isCheck){
				const that = this;
				if(sta)
					this.formData.state = sta;
				if(isCheck){
					this.submitBtn = true;
					this.$http.post("/fwqz/check",this.formData).then(res=>{
						let _data = res.data.data;
						if(_data){
							that.$refs.uToast.show({
								title: '保存成功',
								type: 'success',
								callback: ()=>{
									let pages = getCurrentPages(); // 当前页面
									let prePage = pages[pages.length - 2]; // 前一个页面
									uni.navigateBack({
									     success: function() {
											prePage.onLoad(); // 执行前一个页面的onLoad方法
									     }
									});
								}
							})
						}else{
							that.submitBtn = false;
						}
					}).catch(e=>{
						that.submitBtn = false;
						that.$refs.uToast.show({
							title: '保存失败请稍后重试...',
							type: 'error',
						})
					})
				}else{
					if(this.validateFormData()){
						let files = [];
						// 上传图片拼接
						for(let item of this.fileList){	
							if(item.progress==100){
								files = files.concat(item.response.data);
							}
						}
						this.submitBtn = true;
						this.formData.filePaths = files.join(",");
						// 数据校验
						uni.uploadFile({
							url:this.url,
							filePath:this.signImage,
							name:'file',
							formData:this.formData,
							success: (res) => {
								let _data = JSON.parse(res.data).data;				
								if(_data){
									that.$refs.uToast.show({
										title: '保存成功',
										type: 'success',
										callback: ()=>{
											that.submitBtn = false;
											let pages = getCurrentPages(); // 当前页面
											let prePage = pages[pages.length - 2]; // 前一个页面
											uni.navigateBack({
											     success: function() {
													prePage.onLoad(); // 执行前一个页面的onLoad方法
											     }
											});
										}
									})
								}else{
									that.submitBtn = false;
								}
							},
							fail:(fail) =>{
								that.submitBtn = false;
								that.$refs.uToast.show({
									title: '保存失败请稍后重试...',
									type: 'error',
								})
								
							}
						})
					}
				}
				
			},
			onRemove(index, lists) {
				console.log('图片已被移除')
				this.fileList = lists;
			},
			onUploaded(lists) {
				console.log('onUploaded...');
				this.fileList = lists;
			},
			setLoaction(){
				let locations = this.$auth.getLocationInfo();
				console.log('locations......');
				console.log(locations);
				this.formData.lat = locations.lat;
				this.formData.lng = locations.lng;
				this.formData.location = locations.address;
			},
			retDraw() {
				this.qmBtn = false;
			 	this.handwriting.retDraw()
			 	this.signImage = '';
			},
			
			uploadScaleStart(event){
			 	  this.handwriting.uploadScaleStart(event)
			},
			uploadScaleMove(event){
			 	  this.handwriting.uploadScaleMove(event)
			},
			uploadScaleEnd(event){
			 	  this.handwriting.uploadScaleEnd(event)
			 	  this.isEnd = true;
			},
			subCanvas(){
			 	if(!this.isEnd){
			 		this.$refs.uToast.show({
			 			title: '尚未签名，请签名后保存',
			 			type: 'error'
			 		})
			 		return;
			 	}
			 	  this.handwriting.saveCanvas().then(res=>{
					  this.qmBtn = true;
			 		  this.signImage = res;
					  this.$refs.uToast.show({
					  	title: '签名已完成',
					  	type: 'success'
					  })
			 	  }).catch(err=>{
			 		  console.log(err);
				});		  
			 	  
			},
			checkHasPermission(){
				if(this.formData.id){
					//没有修改权限，或者已审核通过，或者当点内容非本用户，设置内容为禁用状态
					if(this.user.user.auths.indexOf('edit')<0||this.formData.state==='2'|| this.formData.userId != this.user.user.id){
						this.disabled = true;
					}
					//有审核权限，并且未审核状态，并且非本用户内容
					if(this.user.user.auths.indexOf('check')>-1&&this.formData.state==='1'&&this.formData.userId != this.user.user.id){
						this.hasChecked = true;
					}
				}
			},
			//审核通过
			checked(){
				this.save(2,true);
				console.log("审核通过");
			},
			//审核不通过
			unChecked(){
				this.unCheckedModalShow = true;
			},
			// 模态窗点击确认
			confirm(){
				this.save(3,true);
			},
			initUploadImgs(){
				this.cusPreviewImgList = [];
				if(this.formData.filePaths){
					for(let img of this.formData.filePaths){
						this.cusPreviewImgList.push(this.$http.config.uploadPath+img);
						this.imgList.push({url:this.$http.config.uploadPath+img});
					}
					this.formData.filePaths = this.formData.filePaths.join(",");
				}
				if(this.formData.qmPath){
					this.hasSign = true;
					this.signImageURL = this.$http.config.uploadPath+this.formData.qmPath;
					//this.signImage = this.$http.config.uploadPath+this.formData.qmPath;
				}
			},
			previewImg(url) { // 点击预览图片
				
				this.$refs.cusPreviewImg.open(url) // 传入当前选中的图片地址
			}
		},
		onLoad(options) {
			this.formData.userId = this.user.user.id;
			this.handwriting = new Handwriting({
			  lineColor: this.lineColor,
			  slideValue: this.slideValue, // 0, 25, 50, 75, 100
			  canvasName: 'handWriting',
			});
			this.setLoaction();
			let editItem = {};
			if(options.item){
				editItem = JSON.parse(options.item);
				Object.assign(this.formData,editItem);
			}
			this.checkHasPermission();
			this.initUploadImgs();
		}
	}
</script>

<style scoped>
	.wrapper {
	  width: 100%;
	  height: 100%;
	  overflow: hidden;
	  display: flex;
	  align-content: center;
	  flex-direction: column;
	  justify-content: center;
	  font-size: 28upx;
	}
	.handWriting {
	  background: #fff;
	  width: 100%;
	  height: 350upx;
	}
	
	.handCenter {
	  border: 4upx dashed #e9e9e9;
	  flex: 5;
	  overflow: hidden;
	  box-sizing: border-box;
	  width: 90%;
	  margin: 0 auto;
	}
	.buttons{
		display: flex;
		width: 100%;
		margin-top: 20upx;
		justify-content: space-between;
	}
	.commitBtn{
		margin-top: 15rpx;
	}
	.buttons>button{
		display: inline-block;
		font-size: 30upx;
		height: 80upx;
		
	}
	.delBtn {
	  color: #666;
	}
	.subBtn {
	  background: #008ef6;
	  color: #fff;
	  text-align: center;
	  justify-content: center;
	}
	.showimg{
		border: 4upx solid #e9e9e9;
		overflow: hidden;
		width: 90%;
		margin: 0 auto;
		background: #eee;
		height: 350upx;
		align-items: center;
		justify-content: center;
	}
	.showimg>image{
		width: 100%;
		height: 100%;	
	}
	.showimg>text{
		font-size: 40upx;
		color: #888;
	}
	.showSign{
		animation: fadeIn .3s;
		display: flex;
	}
	.hideSign{
		animation: fadeOut .3s;
		display: none;
	}
	@keyframes fadeOut{
	 0% {
			opacity: 1;
			transform: translateY(0px);
		}
	 50% {
		opacity: 0.5;
		transform: translateY(5px);
		 }
	 100%{
		
		opacity: 0; 
		transform: translateY(10px);
		}
	}
	@keyframes fadeIn{
	 0% {opacity: 0; transform: translateY(10px);}
	 50% {opacity: 0.5; transform: translateY(5px);}
	 100%{opacity: 1; transform: translateY(0px);}
	}
	.uploadImg{
		margin: 20rpx;
		width: 150rpx;
		height: 150rpx;
	}
</style>
